<?php

namespace app\admin\model\facrm;

use think\Model;
use traits\model\SoftDelete;
use addons\facrm\model\Area;

class Customer extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'facrm_customer';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    const REMINDDAY = 3;//提醒时间

    protected static function init()
    {
        $forfun = function (&$row) {
            foreach ($row->data as $k => $v) {
                //数组的字段处理成字符串,主要处理是自定义字段多选的值
                if (!empty($v) && is_array($v)) $row->data[$k] = implode(',', $v);
            }
        };

        self::afterUpdate(
            function ($row) {
                $changed = $row->getChangedData();
                if ($changed&&isset($changed['follow_time'])) return;//跟进操作不加日志
                Operatelog::record($row->id, 0, 0,Operatelog::getTitle()?"":"更变资料", json_encode($changed));
            }
        );
        self::afterInsert(function ($row) use ($forfun) {
            //添加操作日志
            Operatelog::record($row->id, 0,0,Operatelog::getTitle()?"":"新增资料", json_encode($row));
        });



        /**
         * 插入前
         */
        self::beforeInsert(function ($row) use ($forfun) {
            $forfun($row);
        });
        /**
         * 更新前
         */
        self::beforeUpdate(function ($row) use ($forfun) {
            $forfun($row);
        });
        self::afterWrite(function ($row) {
            $origin = $row->getOriginData();
            if (isset($row['tags'])) {
                \app\admin\model\facrm\Tag::refresh($row['tags'], isset($origin['tags']) ? $origin['tags'] : '');
            }
        });
    }

    public function getOriginData()
    {
        return $this->origin;
    }

    /**
     * 创建者
     */
    public function createUser()
    {
        return $this->hasOne('\app\admin\model\Admin', 'id', 'create_user_id');
    }

    /**
     * 创建者
     */
    public function ownerUser()
    {
        return $this->hasOne('\app\admin\model\Admin', 'id', 'owner_user_id');
    }

    /**
     * 关联联系人
     * @return \think\model\relation\HasMany
     */
    public function contacts()
    {
        return $this->hasMany('\app\admin\model\facrm\customer\Contacts', 'customer_id', 'id');
    }

    /**
     * 放入公海
     */
    public function discard()
    {
        $this->owner_user_id = 0;
		\app\admin\model\facrm\Operatelog::setTitle(__('放入公海'));
        $this->save();
        //联系人负责人也更改为0
        $contacts = model('\app\admin\model\facrm\customer\Contacts');
       
        $contacts->where('customer_id', $this->id)->update(['owner_user_id' => 0]);
        return true;
    }

    /**
     * 获取将要过期的客户
     * @param $owner_user_id array|integer
     * @return array|bool|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getLose($owner_user_id)
    {
        $config = get_addon_config('facrm');
        //不跟进
        if ($config['lose_day1'] > 0 || ($config['lose_day2'] > 0)) {
            $customerModel = model('\app\admin\model\facrm\Customer');
            $customerModel->where('deal_status', 0);
            if (is_array($owner_user_id)) {
                $customerModel->where('owner_user_id', 'in', $owner_user_id);
            } else {
                $customerModel->where('owner_user_id', $owner_user_id);
            }

            if ($config['lose_day1'] > 0 && $config['lose_day2'] > 0) {
                $customerModel->where(function ($query) use ($config) {
                    $query->where('follow_time', '<', (time() - (($config['lose_day1']+self::REMINDDAY) * 86400) ))->whereOr('collect_time', '<', (time() - (($config['lose_day2']+self::REMINDDAY) * 86400)));
                });
            } elseif ($config['lose_day1'] > 0 && ($config['lose_day2'] <= 0)) {
                $customerModel->where('follow_time', '<', (time() - (($config['lose_day1']+self::REMINDDAY) * 86400)));
            } elseif ($config['lose_day1'] <= 0 && $config['lose_day2'] > 0) {
                $customerModel->where('collect_time', '<', (time() - (($config['lose_day2']+self::REMINDDAY) * 86400)));
            } else {
                return [];
            }
            $lists = $customerModel->fetchSql(false)->field('owner_user_id,id,name')->select();
            return $lists;

        }
        return [];
    }


    /**
     * 获取过期的where查询条件
     * @param $config 插件配置
     * @param int $expire_type 是否获取
     * @return $this
     */
    public function getLoseWhere($config, $expire_type = 0)
    {
        if (!$expire_type) return $this;
        //不跟进
        if ($config['lose_day1'] > 0 || ($config['lose_day2'] > 0)) {
            if ($config['lose_day1'] > 0 && $config['lose_day2'] > 0) {
                $this->where(function ($query) use ($config) {
                    $query->where('follow_time', '<', (time() - (($config['lose_day1']+self::REMINDDAY) * 86400)))->whereOr('collect_time', '<', (time() - (($config['lose_day2']+self::REMINDDAY) * 86400)));
                });
            } elseif ($config['lose_day1'] > 0 && ($config['lose_day2'] <= 0)) {
                $this->where('follow_time', '<', (time() - (($config['lose_day1']+self::REMINDDAY) * 86400)));
            } elseif ($config['lose_day1'] <= 0 && $config['lose_day2'] > 0) {
                $this->where('collect_time', '<', (time() - ($config['lose_day2']+self::REMINDDAY) * 86400));
            }
            $this->where('deal_status','=','0');
        }else{
            $this->where('deal_status','=','-1000');//TODO 为了让相关没有数据
        }
        return $this;
    }

    /**
     * 添加客户
     * @param $params
     * @param int $create_user_id
     * @param int $owner_user_id
     * @param bool $validate 是否校验数据
     */
    public function add($params, $create_user_id = 0, $owner_user_id = 0,$validate=true)
    {
        if ($validate) {
            //系统字段验证
            $cresult = Fields::validateByForm('customer', $params,'system');
            if (!$cresult['status']) {
                $this->error = $cresult['msg'];
                return false;
            }
            //校验数据
            $cresult = Fields::validateByForm('customer', $params);
            if (!$cresult['status']) {
                $this->error = $cresult['msg'];
                return false;
            }
        }
        try {
            if ($validate){
                //采用模型验证
                $name = str_replace("\\model\\", "\\validate\\", get_class($this));
                $this->validateFailException(true)->validate($name . '.add');
            }

            //处理省市区是字符串
            if (isset($params['province'])&&$params['province']&&!intval($params['province'])){
                $params['province']=Area::getIdByName($params['province'],1,0);
            }
            if (isset($params['city'])&&$params['city']&&!intval($params['city'])){
                $params['city']=Area::getIdByName($params['city'],2,isset($params['province'])?$params['province']:0);
            }
            if (isset($params['area'])&&$params['area']&&!intval($params['area'])){
                $params['area']=Area::getIdByName($params['area'],3,isset($params['city'])?$params['city']:0);
            }

			$params['collect_time']=isset($params['collect_time'])?$params['collect_time']:time();
            $result = $this->allowField(true)->isUpdate(false)->save($params);
            if ($result) {
                //自动添加联系人
                $params_contact = [
                    'create_user_id' => isset($params['create_user_id']) ? $params['create_user_id'] : $create_user_id,
                    'owner_user_id' => isset($params['owner_user_id']) ? $params['owner_user_id'] : $owner_user_id,
                    'customer_id' => $this->id,
                    'name' => $params['name'],
                    'mobile' => $params['mobile'],
                    'telephone' => $params['telephone'],
                    'remark' => '自动添加',
                ];
                $this->contacts()->save($params_contact);
            }

        }catch (\Exception $e){
            $this->error=$e->getMessage();
            return  false;
        }

        $insert_id = $this->id;
        unset($this->id);
        return $result ? $insert_id : $result;

    }


    /**
     * 修改
     * @param $params
     * @param bool $validate
     * @return bool|false|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($params,$validate=true){

        if ($validate) {
            //系统字段验证
            $cresult = Fields::validateByForm('customer', $params,'system');
            if (!$cresult['status']) {
                $this->error = $cresult['msg'];
                return false;
            }
            //校验自定义数据
            $cresult = Fields::validateByForm('customer', $params);
            if (!$cresult['status']) {
                $this->error = $cresult['msg'];
                return false;
            }
        }
        //是否采用模型验证
        if ($validate){
            //采用模型验证
            $name = str_replace("\\model\\", "\\validate\\", get_class($this));
            $this->validateFailException(true)->validate($name . '.edit');
        }

        return $this->allowField(true)->save($params);

    }


    /**
     * 删除
     * @param int $id
     */
    public function del($id=null){
        if ($id){
           return ($this->where('id',$id)->find())->del();
        }

        //删除客户跟进记录
        $rlist=\app\admin\model\facrm\Record::where('types','customer')->where('types_id',$this->id)->select();
        foreach ($rlist as $j => $r) {
            $r->delete();
        }
        //删除联系人
        $crlist=\app\admin\model\facrm\customer\Contacts::where('customer_id',$this->id)->select();
        foreach ($crlist as $j => $c) {
            $c->delete();
        }

        //删除商机
        $crlist=\app\admin\model\facrm\Business::where('customer_id',$this->id)->select();
        foreach ($crlist as $j => $b) {
            //删除商机跟进
            $brlist=\app\admin\model\facrm\Record::where('types','business')->where('types_id',$b->id)->select();
            foreach ($brlist as $key => $br) {
                $br->delete();
            }
            $b->delete();
        }

        \app\admin\model\facrm\Operatelog::setTitle(__('删除客户'));
        return   $this->delete();
    }

    /**
     * 真实删除
     * @param int $id
     * @return int|void
     */
    public function trueDel($id=null){
        if ($id){
            return ($this->where('id',$id)->withTrashed()->find())->trueDel();
        }

        //删除客户跟进记录
        $rlist=\app\admin\model\facrm\Record::withTrashed()->where('types','customer')->where('types_id',$this->id)->delete(true);
        //删除联系人
        \app\admin\model\facrm\customer\Contacts::withTrashed()->where('customer_id',$this->id)->delete(true);
        //删除商机
        $crlist=\app\admin\model\facrm\Business::withTrashed()->where('customer_id',$this->id)->select();
        foreach ($crlist as $j => $b) {
            //删除商机跟进
            \app\admin\model\facrm\Record::withTrashed()->where('types','business')->where('types_id',$b->id)->delete(true);
            //删除商机关联联系人
            \app\admin\model\facrm\business\Contacts::where('business_id',$b->id)->delete(true);
            //删除商机关联产品
            \app\admin\model\facrm\business\Product::where('business_id',$b->id)->delete(true);
            $b->delete(true);
        }

        return   $this->delete(true);
    }

    /**
     * 还原
     */
    public function restores($id=null){
        if ($id){
            return ($this->where('id',$id)->withTrashed()->find())->restores();
        }

        //客户跟进记录
        $rlist=\app\admin\model\facrm\Record::withTrashed()->where('types','customer')->where('types_id',$this->id)->select();

        foreach ($rlist as $j => $r) {
            $r->restore();
        }
        //联系人
        $crlist=\app\admin\model\facrm\customer\Contacts::withTrashed()->where('customer_id',$this->id)->select();
        foreach ($crlist as $j => $c) {
            $c->restore();
        }

        //商机
        $crlist=\app\admin\model\facrm\Business::withTrashed()->where('customer_id',$this->id)->select();
        foreach ($crlist as $j => $b) {
            //商机跟进
            $brlist=\app\admin\model\facrm\Record::withTrashed()->where('types','business')->where('types_id',$b->id)->select();
            foreach ($brlist as $j => $br) {
                $br->restore();
            }
            $b->restore();
        }

        return   $this->restore();
    }

}